﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentExport.CSVExport.Interfaces;

namespace FluentExport.CSVExport
{
    public class CSVCompoundSource<TSource> : ICSVCompoundSource<TSource>
    {
        #region Members

        private readonly ICSVExport _csvExport;
        private readonly ICSVExportHelper _csvExportHelper;

        #endregion

        #region Properties

        public ICollection<ICSVSimpleSource> Sources { get; set; }

        public string Format { get; private set; }

        #endregion

        #region Constructors

        public CSVCompoundSource(ICSVExport csvExport, ICSVExportHelper csvExportHelper)
        {
            Sources = new List<ICSVSimpleSource>();

            _csvExport = csvExport;
            _csvExportHelper = csvExportHelper;
        }

        #endregion

        #region Methods

        public ICSVCompoundSource<TSource> Add(Expression<Func<TSource, object>> source)
        {
            var propertyName = _csvExportHelper.GetPropertyName(source);

            Sources.Add(new CSVSimpleSource(_csvExportHelper) { PropertyName = propertyName });

            return this;
        }

        public ICSVExport WithFormat(string format)
        {
            Format = format;
            return _csvExport;
        }
   
        public string GetValue(object data)
        {
            var ret = Sources.Select(m => m.GetValue(data)).ToArray();
            return String.Format(Format,ret);
        }

        #endregion
    }
}
